package com.liao.seckill.service.impl;

import com.liao.seckill.constant.UserConstant;
import com.liao.seckill.dao.UserDao;
import com.liao.seckill.dto.UserDto;
import com.liao.seckill.pojo.TbUser;
import com.liao.seckill.service.UserService;
import com.liao.seckill.utils.JwtTokenUtil;
import com.liao.seckill.vo.ResUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;
    private BCryptPasswordEncoder passwordEncoder;
    private StringRedisTemplate redisTemplate;

    public UserServiceImpl(UserDao userDao, BCryptPasswordEncoder passwordEncoder, StringRedisTemplate redisTemplate) {
        this.userDao = userDao;
        this.passwordEncoder = passwordEncoder;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public ResUser login(UserDto userDto) {
        TbUser tbUser = userDao.findByUsername(userDto.getUsername());
        if (tbUser == null) {
            return null;
        }
        if (!passwordEncoder.matches(userDto.getPassword(), tbUser.getPassword())) {
            return null;
        }
        String token = JwtTokenUtil.generateToken(tbUser);
        redisTemplate.opsForValue().set(UserConstant.TOKEN_KEY_PREFIX + ":" + tbUser.getId()
                , token, UserConstant.TOKEN_EXPIRED_TIME, TimeUnit.SECONDS);
        return new ResUser(tbUser.getId(), tbUser.getUsername(), token);
    }

}
